import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tiktokadult/tools_base/appbar/custom_appbar.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:qr_code_utils/qr_code_utils.dart';

import '../../../../hj_utils/screen.dart';

class QrScanPage extends StatefulWidget {
  static const routeName = '/qr_scan';
  const QrScanPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _QrScanPageState();
  }
}

class _QrScanPageState extends State<QrScanPage> {
  bool isFirst = true;

  Barcode? result;
  QRViewController? controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppbar(
        title: '扫一扫',
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Expanded(
            child: ScanImageView(
              child: _buildQrView(context),
            ),
          ),
          Container(
            height: 174.h,
            padding: EdgeInsets.only(top: 28.h),
            color: Colors.black,
            child: GestureDetector(
                child: Column(
                  children: [
                    Image.asset(
                      "assets/images/hj_mine/icon_image.png",
                      width: 50.w,
                      height: 50.w,
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      '账号凭证',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                      ),
                    )
                  ],
                ),
                onTap: () async {
                  var image = await ImagePickers.pickerPaths(selectCount: 1);

                  QrCodeUtils.decodeFrom(image.first.path ?? "").then((value) {
                    Navigator.pop(context, value);
                  });
                }),
          ),
        ],
      ),
    );
  }

  Future<bool> canReadStorage() async {
    AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
    String androidVersion = androidInfo.version.release;

    PermissionStatus status;

    if (int.parse(androidVersion) <= 12) {
      status = await Permission.storage.request();
    } else {
      status = await Permission.photos.request();
    }

    return status.isGranted;
  }

  Future<bool> getFlashMode() async {
    bool? isOpen = false;
    try {
      isOpen = await controller?.getFlashStatus();
    } catch (_) {}
    return isOpen == true;
  }

  Widget buildFlashBtn(BuildContext context, AsyncSnapshot<bool> snapshot) {
    return snapshot.hasData
        ? Padding(
            padding: EdgeInsets.only(bottom: 24 + MediaQuery.of(context).padding.bottom),
            child: IconButton(
                icon: Icon(snapshot.data == true ? Icons.flash_on : Icons.flash_off),
                color: Colors.white,
                iconSize: 46,
                onPressed: () {
                  controller?.toggleFlash();
                  setState(() {});
                }),
          )
        : Container();
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    var scanArea = screen.screenWidth / 1.48;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(borderColor: Colors.white, borderRadius: 0, borderLength: 20, borderWidth: 5, cutOutSize: scanArea),
      onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
        controller.dispose();
        Navigator.pop(context, result?.code);
      });
    });
  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('no Permission')),
      );
    }
  }
}

class ScanImageView extends StatefulWidget {
  final Widget? child;

  const ScanImageView({super.key, this.child});

  @override
  State<StatefulWidget> createState() {
    return _ScanImageViewState();
  }
}

class _ScanImageViewState extends State<ScanImageView> with TickerProviderStateMixin {
  AnimationController? controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 1000));
    controller?.repeat(reverse: true);
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
        animation: controller!,
        builder: (BuildContext context, Widget? child) => CustomPaint(
              foregroundPainter: _ScanPainter(
                controller!.value,
                Colors.white,
                Colors.green,
              ),
              willChange: true,
              child: widget.child,
            ));
  }
}

class _ScanPainter extends CustomPainter {
  double value = 0.0;
  Color borderColor = Colors.white;
  Color scanColor = Colors.green;
  Paint? _paint;

  _ScanPainter(this.value, this.borderColor, this.scanColor);

  @override
  void paint(Canvas canvas, Size size) {
    if (_paint == null) {
      initPaint();
    }
    // canvas.drawColor(Color(0xFF000000), BlendMode.dst);
    double width = size.width;
    double height = size.height;

    double boxWidth = size.width * 2 / 3;
    double boxHeight = boxWidth;

    double left = (width - boxWidth) / 2;
    double top = (height - boxHeight) / 2;
    double bottom = boxHeight + top;
    double right = left + boxWidth;
    _paint!.color = borderColor;
    // final rect = Rect.fromLTWH(left, top, boxWidth, boxHeight);
    // canvas.drawRect(rect, _paint);

    _paint!.strokeWidth = 3;
    double linew = 46;
    Path path1 = Path()
      ..moveTo(left, top + linew)
      ..lineTo(left, top)
      ..lineTo(left + linew, top);
    canvas.drawPath(path1, _paint!);
    Path path2 = Path()
      ..moveTo(left, bottom - linew)
      ..lineTo(left, bottom)
      ..lineTo(left + linew, bottom);
    canvas.drawPath(path2, _paint!);
    Path path3 = Path()
      ..moveTo(right, bottom - linew)
      ..lineTo(right, bottom)
      ..lineTo(right - linew, bottom);
    canvas.drawPath(path3, _paint!);
    Path path4 = Path()
      ..moveTo(right, top + linew)
      ..lineTo(right, top)
      ..lineTo(right - linew, top);
    canvas.drawPath(path4, _paint!);

    // _paint!.color = scanColor;
    // // _paint.strokeWidth = 1;
    //
    // final scanRect = Rect.fromLTWH(
    //     left + 30, top + 10 + (value * (boxHeight - 60)), boxWidth - 60, 1);
    //
    // _paint!.shader = const LinearGradient(colors: <Color>[
    //   Colors.white10,
    //   Colors.white,
    //   Colors.white10,
    // ], stops: [
    //   0.0,
    //   0.5,
    //   1,
    // ]).createShader(scanRect);
    //
    // canvas.drawRect(scanRect, _paint!);
//     ParagraphBuilder pb = ParagraphBuilder(ParagraphStyle(
//       textAlign: TextAlign.center,
//       fontWeight: FontWeight.w300,
//       fontStyle: FontStyle.normal,
//       fontSize: 15.0,
//     ));
//     pb.pushStyle(ui.TextStyle(color: Colors.white));
//     pb.addText("对准二维码，即可自动识别");
//
// // 设置文本的宽度约束
//     ParagraphConstraints pc = const ParagraphConstraints(width: 200);
// // 这里需要先layout,将宽度约束填入，否则无法绘制
//     Paragraph paragraph = pb.build()..layout(pc);
//     // print(paragraph.width);
//     Offset offset =
//         Offset((size.width - paragraph.width) / 2, boxHeight + top + 30);
//     _paint!.color = const Color(0xFFededed);
//     canvas.drawParagraph(paragraph, offset);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }

  void initPaint() {
    _paint = Paint()
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round
      ..strokeJoin = StrokeJoin.round;
  }
}
